#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mypub 
import sys
import os 
import socket 
import time 
import mypub 
import struct 
from mypub import *
from PyQt4 import QtCore


action_list={ 
	1:"跳舞",
	2:"挥手",
	3:"坐下",
}
attire_opt_list={ 
	0:"脱下",
	1:"穿上",
}


class proto( QtCore.QObject): 
	def getsock(self):
		return self.sock

	def getheaderlen(self):
		return self.headerlen
	def __init__(self,ip,port):
		QtCore.QObject.__init__(self)
		self.headerlen=17
		self.ip=ip;
		self.port=port
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     
		self.getsock().connect((self.ip,self.port))     
		self.recvbuf=""
		#设置为非阻塞连接	
		self.sock.setblocking(0)
		#print "init succ"
	def setblocking(self, flag):
		self.sock.setblocking(flag)

	def pack(self,cmdid,userid,primsg ):
		#mk header
		result=0
		headermsg=struct.pack(">LBLLL", self.getheaderlen()+len(primsg),1,cmdid,userid, result);
		return  headermsg+ primsg  	
		pass
	def test(self):
		self.emit(QtCore.SIGNAL('playerLogin(PyQt_PyObject)') ,"sssss")
		pass



	def login(self,userid,passwd,regflag=0):
		#登入	
		primsg=struct.pack(">32sL",mypub.get_md5( passwd),regflag );
		sendbuf=self.pack(101,userid,primsg); 
		self.getsock().send(sendbuf) 
		pass

	def get_online_list(self,startid,endid):
		#得到 online 列表
		primsg=struct.pack(">LLL",startid,endid,0 );
		sendbuf=self.pack(103,250,primsg); 
		self.getsock().send(sendbuf) 
		pass
	def online_login(self,userid,onlineid,key,key2):
		#online 登入	
		self.userid=userid;
		primsg=struct.pack(">h16sL16s",onlineid,key2,16, key );
		sendbuf=self.pack(201,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass
	def buy_item(self,itemid,count ):
		"""购买"""
		primsg=struct.pack(">LL",itemid,count );
		sendbuf=self.pack(501,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass

	def throw_item(self,itemid,x,y):
		"""投掷东西"""
		primsg=struct.pack(">LLL",itemid,x,y );
		sendbuf=self.pack(306,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass

	def gen_rand_item(self,itemid):
		primsg=struct.pack(">L",itemid );
		sendbuf=self.pack(320,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass
	def get_rand_item(self,posid):
		primsg=struct.pack(">LL",posid,0);
		sendbuf=self.pack(318,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass

	def move(self,x,y ):
		"""走动"""
		primsg=struct.pack(">LLL",x,y,0);
		sendbuf=self.pack(303,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass
	def action(self, actionid, flag=0 ):
		"""动作"""
		primsg=struct.pack(">LB",actionid,flag );
		sendbuf=self.pack(305,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass

	def talk(self,msg ):
		"""走动"""
		msglen=len(msg)
		primsg=struct.pack(">LL"+str(msglen)+"s",0,msglen,msg);
		sendbuf=self.pack(302,self.userid,primsg); 
		#print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass
	






	def cd_map(self,mapid):
		primsg="";
		sendbuf=self.pack(402,self.userid,primsg); 
		print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 

		primsg=struct.pack(">LL",mapid,0);
		sendbuf=self.pack(401,self.userid,primsg); 
		print mypub.print_hex_16(sendbuf);
		self.getsock().send(sendbuf) 
		pass




	def getrecvmsg(self):
		"""得到一个完整报文"""
		tmp_recvfbuf=""
		try :
			tmp_recvfbuf= self.getsock().recv(4096)     
			#print "getmsg"
		except socket.error, msg:
			#print msg
			if(msg[0]<>11 ):
				#print msg
				exit(1) 	
			pass
		self.recvbuf=self.recvbuf+tmp_recvfbuf	
		#得到报文		
		if (len( self.recvbuf)<=4):
			return False 
		else:
		 	#得到长度
		 	recvmsg_arr=struct.unpack_from(">L",self.recvbuf);
			recvmsg_len=recvmsg_arr[0];
			returnmsg=self.recvbuf[0:recvmsg_len];
			self.recvbuf=self.recvbuf[recvmsg_len:];

			pri_len=recvmsg_len- self.getheaderlen();
			return struct.unpack(">LBLLl"+str(pri_len)+"s", returnmsg);
	def dealmsg(self):
		out_info=self.getrecvmsg();
		if (out_info):
			proto_len,version,cmdid,userid,result, pri_msg=out_info;
			#print cmdid, result, userid ,
			if (cmdid==10003 ): 
				print "<消息> 来自:", pri_msg[12:12+16] , "内容:", pri_msg[44:]  
			elif(cmdid==303) :
				#走路 
				auserid, x , y, z =struct.unpack(">LLLL",pri_msg );
				self.emit(QtCore.SIGNAL('playerMove(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)'),
						auserid,x,y )
	
			elif(cmdid==402):
				#进入或离开
				flag , auserid =struct.unpack(">LL",pri_msg );
				print "用户 ",auserid, "进入或离开flag" ,flag
			elif(cmdid==302):
				#聊天  
				auserid,anick =struct.unpack(">L16s",pri_msg[0:20] );
				print "聊天 ",auserid,anick, "内容:", pri_msg[28:];
			elif(cmdid==306):
				#投弹
				auserid, attireid , x, y =struct.unpack(">LLLL",pri_msg );
				print "投弹:用户",auserid,"投掷物品",attireid, "x", x ,"y",y;
			elif(cmdid==201):
				#登入
				self.emit(QtCore.SIGNAL('playerLogin(PyQt_PyObject)') ,pri_msg)
	
			elif(cmdid==305):
				#动作
				auserid, actionid,flag =struct.unpack(">LLB",pri_msg);
				print "动作:用户",auserid ,"动作:",action_list[actionid], "flag:", flag   ;
	
			elif(cmdid==503):
				#换上或脱下
				auserid,attireidcount=struct.unpack(">LL",pri_msg[0:8]);
				print "换上或脱下:用户",auserid ,"物品个数:",attireidcount;
				for i in range(attireidcount):
					attireid,flag=struct.unpack(">LB",pri_msg[8+i*5:8+5+i*5]) ;
					print "\t 装扮ID:",attireid, "操作:",attire_opt_list[flag]
			elif(cmdid==401):
				#用户信息
				auserid, anick =struct.unpack(">L16s",pri_msg[0:20] );
				attireidcount,=struct.unpack(">B",pri_msg[111:112]);
				print "用户信息?!:",auserid,"昵称:",anick ,"装扮个数:",attireidcount
				for i in range(attireidcount):
					attireid,=struct.unpack(">L",pri_msg[112+i*4:112+4+i*4]) ;
					print "\t 装扮ID:",attireid 
				print "未解包:"
				print print_hex_16(pri_msg[20:111] );
			else:
				#print pri_msg
				print print_hex_16(pri_msg );
	
		pass
			
def mole_login(loginser_ip,loginser_port,onlineid,userid, passwd ):
	p=proto(loginser_ip,loginser_port)
	p.login(userid, passwd);
	p.setblocking(1)
	login_out=p.getrecvmsg();
	#print  print_hex_16( login_out[5])
	key=login_out[5][4:20]
	md5str = "Bye bYe crAzy B Aby in Our ProgRAm?"
	id1,=struct.unpack(">L",key[10:14] );
	id2,=struct.unpack(">L",key[3:7] );
	k="%u%.11s%u"%(id1,md5str[5:16], id2)
	key2=get_md5(k)
	key2=key2[6:22]
	#得到online列表  
	p.get_online_list(onlineid,onlineid+10 )
	out_msg=p.getrecvmsg();
	print  print_hex_16( out_msg[5])
	online_id,online_count=struct.unpack(">LL",out_msg[5][4:12]);
	print "online_id", online_id, "online_count", online_count
	online_ip= out_msg[5][12:28].split('\0');
	online_port,=struct.unpack(">h",out_msg[5][28:30]);
	#print online_ip, online_port
	

	p=proto(online_ip[0] ,online_port )
	p.online_login(userid,onlineid ,key ,key2  );
	return p
	pass
